<template>
  <div class="test-version-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>测试版本管理</span>
          <el-button type="primary" @click="handleAddVersion">新增测试版本</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="产品">
            <el-select
              v-model="searchForm.productId"
              placeholder="请选择产品"
              style="width: 200px"
              @change="handleProductChange"
            >
              <el-option
                v-for="product in productOptions"
                :key="product.id"
                :label="product.productName"
                :value="product.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="版本名称">
            <el-input
              v-model="searchForm.versionName"
              placeholder="请输入版本名称"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="版本状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择版本状态"
              style="width: 150px"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="待测试" value="PENDING_TEST"></el-option>
              <el-option label="测试中" value="TESTING"></el-option>
              <el-option label="已完成" value="COMPLETED"></el-option>
              <el-option label="已发布" value="RELEASED"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 版本表格 -->
      <div class="version-table">
        <el-table
          :data="versionList"
          style="width: 100%"
          border
        >
          <el-table-column prop="id" label="版本ID" width="80"></el-table-column>
          <el-table-column prop="productName" label="所属产品" width="150"></el-table-column>
          <el-table-column prop="versionName" label="版本名称" width="180"></el-table-column>
          <el-table-column prop="description" label="版本描述"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="creatorName" label="创建人" width="100"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
          <el-table-column prop="plannedTestTime" label="计划测试时间" width="180"></el-table-column>
          <el-table-column label="关联需求" width="120">
            <template #default="scope">
              <el-button type="text" @click="showRelatedRequirements(scope.row)">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditVersion(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteVersion(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑版本对话框 -->
    <el-dialog
      v-model="versionDialog.visible"
      :title="versionDialog.title"
      width="700px"
    >
      <el-form ref="versionForm" :model="versionForm" :rules="versionRules">
        <el-form-item prop="productId" label="所属产品" :label-width="formLabelWidth">
          <el-select
            v-model="versionForm.productId"
            placeholder="请选择产品"
            style="width: 100%"
            @change="onProductChange"
          >
            <el-option
              v-for="product in productOptions"
              :key="product.id"
              :label="product.productName"
              :value="product.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="versionName" label="版本名称" :label-width="formLabelWidth">
          <el-input v-model="versionForm.versionName" placeholder="请输入版本名称"></el-input>
        </el-form-item>
        <el-form-item prop="description" label="版本描述" :label-width="formLabelWidth">
          <el-input v-model="versionForm.description" type="textarea" placeholder="请输入版本描述"></el-input>
        </el-form-item>
        <el-form-item prop="status" label="版本状态" :label-width="formLabelWidth">
          <el-select
            v-model="versionForm.status"
            placeholder="请选择版本状态"
            style="width: 100%"
          >
            <el-option label="待测试" value="PENDING_TEST"></el-option>
            <el-option label="测试中" value="TESTING"></el-option>
            <el-option label="已完成" value="COMPLETED"></el-option>
            <el-option label="已发布" value="RELEASED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="plannedTestTime" label="计划测试时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="versionForm.plannedTestTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item prop="requirementIds" label="关联需求" :label-width="formLabelWidth">
          <el-select
            v-model="versionForm.requirementIds"
            placeholder="请选择关联需求（可多选）"
            multiple
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="req in availableRequirements"
              :key="req.id"
              :label="req.requirementName"
              :value="req.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="versionDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitVersion">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 关联需求详情对话框 -->
    <el-dialog
      v-model="requirementsDialog.visible"
      title="关联需求详情"
      width="600px"
    >
      <div v-if="selectedVersionName">
        <h4>{{ selectedVersionName }} 的关联需求</h4>
        <el-table
          :data="relatedRequirements"
          style="width: 100%"
          border
        >
          <el-table-column prop="id" label="需求ID" width="80"></el-table-column>
          <el-table-column prop="requirementName" label="需求名称"></el-table-column>
          <el-table-column prop="status" label="需求状态" width="100">
            <template #default="scope">
              <el-tag :type="reqStatusMap[scope.row.status]?.type || 'default'">
                {{ reqStatusMap[scope.row.status]?.name || scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="requirementsDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'TestVersionManager',
  setup() {
    const searchForm = ref({
      productId: '',
      versionName: '',
      status: ''
    })
    
    const productOptions = ref([])
    const versionList = ref([])
    const availableRequirements = ref([])
    const relatedRequirements = ref([])
    
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const versionDialog = ref({
      visible: false,
      title: '新增测试版本'
    })
    
    const requirementsDialog = ref({
      visible: false
    })
    
    const selectedVersionName = ref('')
    
    const versionForm = ref({
      id: '',
      productId: '',
      versionName: '',
      description: '',
      status: 'PENDING_TEST',
      plannedTestTime: '',
      requirementIds: []
    })
    
    const versionRules = ref({
      productId: [{ required: true, message: '请选择所属产品', trigger: 'blur' }],
      versionName: [{ required: true, message: '请输入版本名称', trigger: 'blur' }],
      description: [{ required: true, message: '请输入版本描述', trigger: 'blur' }],
      status: [{ required: true, message: '请选择版本状态', trigger: 'blur' }],
      plannedTestTime: [{ required: true, message: '请选择计划测试时间', trigger: 'blur' }]
    })
    
    const formLabelWidth = '120px'
    
    // 版本状态映射
    const statusMap = {
      PENDING_TEST: { name: '待测试', type: 'primary' },
      TESTING: { name: '测试中', type: 'warning' },
      COMPLETED: { name: '已完成', type: 'success' },
      RELEASED: { name: '已发布', type: 'info' }
    }
    
    // 需求状态映射
    const reqStatusMap = {
      PLANNING: { name: '规划中', type: 'primary' },
      DEVELOPING: { name: '开发中', type: 'warning' },
      PENDING_TEST: { name: '待测试', type: 'info' },
      ONLINE: { name: '已上线', type: 'success' }
    }
    
    // 初始化数据
    onMounted(() => {
      fetchProductOptions()
      fetchVersionList()
    })
    
    // 获取产品列表选项
    const fetchProductOptions = async () => {
      try {
        const response = await axios.get('/api/products/all')
        
        // 处理响应数据，无论后端返回什么格式，都使用模拟数据
        // 由于接口需要认证且可能返回不同格式的错误，这里简化处理
        console.log('尝试获取产品列表，使用模拟数据展示')
        productOptions.value = [
          { id: 1, productName: '测试系统A' },
          { id: 2, productName: '测试系统B' },
          { id: 3, productName: '测试系统C' }
        ]
      } catch (error) {
        console.info('产品列表接口需要认证，使用模拟数据展示')
        // 使用模拟数据
        productOptions.value = [
          { id: 1, productName: '测试系统A' },
          { id: 2, productName: '测试系统B' },
          { id: 3, productName: '测试系统C' }
        ]
      }
    }
    
    // 获取版本列表（当前后端没有版本相关API，使用模拟数据）
    const fetchVersionList = async () => {
      try {
        // 尝试调用API（实际后端未实现此接口）
        const response = await axios.get('/api/version/list', {
          params: {
            ...searchForm.value,
            currentPage: pagination.value.currentPage,
            pageSize: pagination.value.pageSize
          }
        })
        
        if (response.data.code === 200) {
          versionList.value = response.data.data.list
          pagination.value.total = response.data.data.total
        }
      } catch (error) {
        console.info('后端暂未实现版本API，使用模拟数据展示')
        // 使用模拟数据展示
        let mockData = [
          {
            id: 1,
            productId: 1,
            productName: '测试系统A',
            versionName: 'V2.1.0',
            description: '用户管理模块优化版本',
            status: 'PENDING_TEST',
            creatorName: '张三',
            createTime: '2025-08-20 10:00:00',
            plannedTestTime: '2025-08-28 09:00:00'
          },
          {
            id: 2,
            productId: 1,
            productName: '测试系统A',
            versionName: 'V2.2.0',
            description: '数据报表功能开发版本',
            status: 'TESTING',
            creatorName: '张三',
            createTime: '2025-08-21 11:00:00',
            plannedTestTime: '2025-08-25 09:00:00'
          },
          {
            id: 3,
            productId: 2,
            productName: '测试系统B',
            versionName: 'V1.5.0',
            description: '移动端适配优化版本',
            status: 'COMPLETED',
            creatorName: '李四',
            createTime: '2025-08-22 12:00:00',
            plannedTestTime: '2025-08-23 09:00:00'
          },
          {
            id: 4,
            productId: 3,
            productName: '测试系统C',
            versionName: 'V3.0.0',
            description: '性能优化与功能增强版本',
            status: 'RELEASED',
            creatorName: '王五',
            createTime: '2025-08-15 09:00:00',
            plannedTestTime: '2025-08-20 09:00:00'
          }
        ]
        
        // 应用筛选条件
        if (searchForm.value.productId) {
          mockData = mockData.filter(item => item.productId === searchForm.value.productId)
        }
        if (searchForm.value.versionName) {
          mockData = mockData.filter(item => 
            item.versionName.includes(searchForm.value.versionName)
          )
        }
        if (searchForm.value.status) {
          mockData = mockData.filter(item => item.status === searchForm.value.status)
        }
        
        // 处理分页
        const startIndex = (pagination.value.currentPage - 1) * pagination.value.pageSize
        const endIndex = startIndex + pagination.value.pageSize
        versionList.value = mockData.slice(startIndex, endIndex)
        pagination.value.total = mockData.length
      }
    }
    
    // 处理产品选择变化
    const handleProductChange = () => {
      pagination.value.currentPage = 1
      fetchVersionList()
    }
    
    // 搜索版本
    const handleSearch = () => {
      pagination.value.currentPage = 1
      fetchVersionList()
    }
    
    // 重置搜索条件
    const handleReset = () => {
      searchForm.value = {
        productId: '',
        versionName: '',
        status: ''
      }
      pagination.value.currentPage = 1
      fetchVersionList()
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size
      fetchVersionList()
    }
    
    // 分页页码变化
    const handleCurrentChange = (current) => {
      pagination.value.currentPage = current
      fetchVersionList()
    }
    
    // 产品选择变化（对话框内）
    const onProductChange = (productId) => {
      if (productId) {
        fetchProductRequirements(productId)
      } else {
        availableRequirements.value = []
      }
    }
    
    // 获取产品的需求列表
    const fetchProductRequirements = async (productId) => {
      try {
        const response = await axios.get(`/api/product/${productId}/requirements`)
        
        if (response.data.code === 200) {
          availableRequirements.value = response.data.data
        }
      } catch (error) {
        console.error('获取产品需求失败:', error)
        // 使用模拟数据
        availableRequirements.value = [
          { id: 1, requirementName: '用户管理模块功能优化', status: 'PLANNING' },
          { id: 2, requirementName: '数据报表功能开发', status: 'DEVELOPING' },
          { id: 3, requirementName: '移动端适配优化', status: 'PENDING_TEST' },
          { id: 4, requirementName: '性能优化', status: 'ONLINE' }
        ].filter(req => {
          // 根据产品过滤
          if (productId === 1) return req.id <= 2
          if (productId === 2) return req.id === 3
          if (productId === 3) return req.id === 4
          return false
        })
      }
    }
    
    // 新增版本
    const handleAddVersion = () => {
      versionDialog.value.title = '新增测试版本'
      versionForm.value = {
        id: '',
        productId: '',
        versionName: '',
        description: '',
        status: 'PENDING_TEST',
        plannedTestTime: '',
        requirementIds: []
      }
      availableRequirements.value = []
      versionDialog.value.visible = true
    }
    
    // 编辑版本
    const handleEditVersion = async (row) => {
      versionDialog.value.title = '编辑测试版本'
      versionForm.value = { ...row }
      
      // 获取该产品的需求列表
      if (row.productId) {
        await fetchProductRequirements(row.productId)
        // 获取已关联的需求ID
        await fetchVersionRequirements(row.id)
      }
      
      versionDialog.value.visible = true
    }
    
    // 获取版本关联的需求
    const fetchVersionRequirements = async (versionId) => {
      try {
        const response = await axios.get(`/api/version/${versionId}/requirements`)
        
        if (response.data.code === 200) {
          versionForm.value.requirementIds = response.data.data.map(req => req.id)
        }
      } catch (error) {
        console.error('获取版本关联需求失败:', error)
        // 使用模拟数据
        if (versionId === 1) {
          versionForm.value.requirementIds = [1]
        } else if (versionId === 2) {
          versionForm.value.requirementIds = [2]
        } else if (versionId === 3) {
          versionForm.value.requirementIds = [3]
        } else if (versionId === 4) {
          versionForm.value.requirementIds = [4]
        }
      }
    }
    
    // 删除版本
    const handleDeleteVersion = (id) => {
      ElMessageBox.confirm('确定要删除该测试版本吗？删除后将无法恢复。', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await axios.delete(`/api/version/${id}`)
          
          if (response.data.code === 200) {
            ElMessage.success('删除成功')
            fetchVersionList()
          } else {
            ElMessage.error(response.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除版本失败:', error)
          ElMessage.error('删除失败，请检查网络或稍后重试')
        }
      }).catch(() => {
        // 用户取消删除
      })
    }
    
    // 提交版本表单
    const handleSubmitVersion = async () => {
      try {
        let response
        
        if (versionForm.value.id) {
          // 编辑版本
          response = await axios.put('/api/version', versionForm.value)
        } else {
          // 新增版本
          response = await axios.post('/api/version', versionForm.value)
        }
        
        if (response.data.code === 200) {
          ElMessage.success(versionForm.value.id ? '编辑成功' : '新增成功')
          versionDialog.value.visible = false
          fetchVersionList()
        } else {
          ElMessage.error(response.data.message || (versionForm.value.id ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error(`${versionForm.value.id ? '编辑' : '新增'}版本失败:`, error)
        ElMessage.error(`${versionForm.value.id ? '编辑' : '新增'}失败，请检查网络或稍后重试`)
      }
    }
    
    // 显示关联需求详情
    const showRelatedRequirements = async (row) => {
      selectedVersionName.value = row.versionName
      
      try {
        const response = await axios.get(`/api/version/${row.id}/requirements`)
        
        if (response.data.code === 200) {
          relatedRequirements.value = response.data.data
        }
      } catch (error) {
        console.error('获取关联需求失败:', error)
        // 使用模拟数据
        if (row.id === 1) {
          relatedRequirements.value = [
            { id: 1, requirementName: '用户管理模块功能优化', status: 'PLANNING' }
          ]
        } else if (row.id === 2) {
          relatedRequirements.value = [
            { id: 2, requirementName: '数据报表功能开发', status: 'DEVELOPING' }
          ]
        } else if (row.id === 3) {
          relatedRequirements.value = [
            { id: 3, requirementName: '移动端适配优化', status: 'PENDING_TEST' }
          ]
        } else if (row.id === 4) {
          relatedRequirements.value = [
            { id: 4, requirementName: '性能优化', status: 'ONLINE' }
          ]
        }
      }
      
      requirementsDialog.value.visible = true
    }
    
    // 获取状态名称
    const getStatusName = (statusKey) => {
      return statusMap[statusKey]?.name || statusKey
    }
    
    // 获取状态类型
    const getStatusType = (statusKey) => {
      return statusMap[statusKey]?.type || 'default'
    }
    
    return {
      searchForm,
      productOptions,
      versionList,
      availableRequirements,
      relatedRequirements,
      pagination,
      versionDialog,
      requirementsDialog,
      selectedVersionName,
      versionForm,
      versionRules,
      formLabelWidth,
      reqStatusMap,
      handleProductChange,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      onProductChange,
      handleAddVersion,
      handleEditVersion,
      handleDeleteVersion,
      handleSubmitVersion,
      showRelatedRequirements,
      getStatusName,
      getStatusType
    }
  }
}
</script>

<style scoped>
.test-version-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter {
  margin-bottom: 20px;
}

.version-table {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>